<script setup lang="ts">
  import { defineAsyncComponent, onMounted, ref } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { cloneDeep } from 'lodash-es'
  import moment from 'moment'
  import routeComponentName from '@/config/route-component-name'
  import ComponentTypeList from './component-type-list/index.vue'
  import Screen from './screen/index.vue'
  import Setting from './setting/index.vue'
  import { HMessageBox } from '@/components/common/message'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  import { ComponentTypeRow, ComponentListItem } from '../hooks/types'
  import { useTemplateForm } from '../hooks/useTemplate'
  import { useFindTemplateById } from '../hooks/useTemplateList'

  defineOptions({
    name: routeComponentName.order.customForm,
  })

  const PreviewModal = defineAsyncComponent(() => import('./preview-modal/index.vue'))
  const { template, findLoading: findTemplateLoading, findTemplate } = useFindTemplateById()
  const {
    form,
    componentList,
    formSaveLoading,
    formSave,
    resetForm,
    setFormId,
    setFormName,
    setFormStatus,
    setComponentList,
    setFormCreateTime,
    setFormUpdateTime,
  } = useTemplateForm()

  const previewModalVisible = ref(false)
  const tagsViewStore = useTagsViewStore()
  const route = useRoute()
  const router = useRouter()
  const currentDragComponentType = ref<ComponentTypeRow>({
    text: '',
    type: 'input',
  })
  const updateingComponent = ref<ComponentListItem | null>(null)
  const templateId = ref('')

  const handleDrag = (componentType: ComponentTypeRow) => {
    currentDragComponentType.value = componentType
  }

  const handleDragEnd = (componentType: ComponentTypeRow) => {
    currentDragComponentType.value = componentType
  }

  /**
   * 中心面板的组件点击事件
   * 主要是更新组件的部分属性，比如：标签的内容、位置，是否要删除…………
   * @param {ComponentListItem} component - 需要更新的组件
   */
  const handleScreenComponentClick = (component: ComponentListItem) => {
    updateingComponent.value = component
  }

  const handleUpdateComponent = (component: ComponentListItem) => {
    updateingComponent.value = component
  }

  const closePage = () => {
    tagsViewStore.delView(route.path)
    router.push({ path: '/order/custom/templates' })
    // resetForm()
  }

  const onSave = async () => {
    if (!form.value.name) {
      HMessageBox.error('请输入模板名称')
      return
    }

    const now = moment().format('YYYY-MM-DD HH:mm:ss')
    !form.value.id && setFormCreateTime(now)
    setFormUpdateTime(now)

    const _componentList = cloneDeep(componentList.value)
    _componentList
      .filter((item) => item.type === 'single-select')
      .forEach((item) => {
        item.singleSelectConfig.beControlVisibleRules.forEach((rule) => {
          const componentIndex = _componentList.findIndex(
            (component) => component.id === rule.componentId,
          )
          if (componentIndex >= 0) {
            _componentList[componentIndex].beControlVisible = true
          }
        })
        return item
      })
    setComponentList(_componentList)
    await formSave()
    tagsViewStore.delView(route.path)
    router.push({ path: '/order/custom/templates', query: { isUpdate: 1 } })
  }

  onMounted(async () => {
    templateId.value = route.params.id as string
    if (templateId.value) {
      await findTemplate(templateId.value)
      if (template.value) {
        setFormName(template.value.name)
        setFormId(template.value.id)
        setFormCreateTime(template.value.createTime)
        setFormUpdateTime(template.value.updateTime)
        setFormStatus(template.value.status)
        setComponentList(template.value.componentList)
      }
      return
    }
    resetForm()
  })
</script>

<template>
  <div v-loading="formSaveLoading || findTemplateLoading" class="order-custom-form">
    <div class="container">
      <div class="header">
        <div class="title">
          <div class="text">
            <span class="required">*</span>
            模板名称：
          </div>
          <el-input placeholder="请输入模板名称" :model-value="form.name" @input="setFormName" />
        </div>
        <div class="btn-group">
          <h-plain-button @click="previewModalVisible = true">预览</h-plain-button>
          <h-plain-button @click="onSave">保存</h-plain-button>
          <h-button @click="closePage">取消</h-button>
        </div>
      </div>
      <div class="main">
        <component-type-list @on-drag="handleDrag" @on-drag-end="handleDragEnd" />
        <div class="screen">
          <Screen
            :component-type="currentDragComponentType"
            :need-update-component="updateingComponent"
            @component-click="handleScreenComponentClick"
          />
        </div>
        <Setting
          :need-update-component="updateingComponent"
          :template-id="templateId"
          @update-component="handleUpdateComponent"
        />
      </div>
    </div>

    <preview-modal v-model="previewModalVisible" :template="form" />
  </div>
</template>

<style scoped lang="scss">
  .order-custom-form {
    height: calc(100vh - 92px);
    width: 100%;
    box-sizing: border-box;
    padding: 12px;

    .container {
      display: flex;
      flex-direction: column;
      width: 100%;
      height: 100%;
      background-color: #fff;
      padding: 12px;
      box-sizing: border-box;
      row-gap: 12px;

      .header {
        display: flex;
        justify-content: space-between;

        .title {
          display: flex;
          align-items: center;

          .text {
            white-space: nowrap;

            .required {
              color: #f56767;
            }
          }
        }

        .btn-group {
          display: flex;
          column-gap: 5px;
        }
      }

      .main {
        height: 0;
        display: flex;
        column-gap: 12px;
        flex: 1;

        .screen {
          display: flex;
          flex: 1;
          width: 0;
          height: 100%;
          box-shadow: 0 0 4px rgba($color: #000000, $alpha: 0.1);
        }
      }
    }
  }
</style>
